using Digitalmes.Domain.Entities.Mes.Equipments;

namespace Digitalmes.Application.Mes.Equipments.Alarms.Commands;

/// <summary>
/// 警报定义创建命令。
/// </summary>
public sealed record CreateAlarmItemCommand(EquipAlarmItemDto AlarmItem) : IRequest<IResult<bool>>;

internal sealed class CreateAlarmItemCommandHandler(IRepository<EquipAlarmItem> repo) : IRequestHandler<CreateAlarmItemCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(CreateAlarmItemCommand request, CancellationToken cancellationToken)
    {
        if (await repo.IsAnyAsync(m => m.LineCode == request.AlarmItem.LineCode
            && m.WorkCenter == request.AlarmItem.WorkCenter
            && m.Index == request.AlarmItem.Index, cancellationToken))
        {
            return Result.Failure("警报定义索引编号已存在");
        }

        var alarmItem = request.AlarmItem.Adapt<EquipAlarmItem>();

        var ok = await repo.InsertAsync(alarmItem, cancellationToken);
        return Result.From(ok);
    }
}
